//
//  SAOpenVipWKWebVC.m
//  saasRetail
//
//  Created by ice on 2024/10/8.
//

#import "SAOpenVipWKWebVC.h"
#import "HDWKWebView.h"
#import "SAMarketingAppCreateOrderAPI.h"
#import "SACreateOrderModel.h"
#import <WechatOpenSDK/WXApi.h>
#import "SAMarketingPayStatusAPI.h"
#import "SAPayStatusModel.h"

@interface SAOpenVipWKWebVC ()<HTTPAPIDelegate>

@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) SAMarketingAppCreateOrderAPI *growthCreateOrderAPI;
@property (nonatomic, strong) SACreateOrderModel *orderModel;
@property (nonatomic, strong) SAMarketingPayStatusAPI *marketingPayStatusAPI;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSDictionary *dataDic;
@property (nonatomic, strong) HDWKWebView *webView;

@end

@implementation SAOpenVipWKWebVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxCancelPay) name:@"WXUserCancelPay" object:nil];
}

-(instancetype)initWithUrl:(NSString *)url AndDataDic:(NSDictionary *)dic; {
    if (self =  [super init]) {
        self.url = url;
        self.dataDic = dic;
        [self initUI];
    }
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
   if (self.growthCreateOrderAPI == api) {
        self.orderModel = [SACreateOrderModel mj_objectWithKeyValues:data[@"data"]];
        [self wxPayOrder];
       if (self.timer != nil) {
           [self.timer invalidate];
           self.timer = nil;
       }
       self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
   }else if (self.marketingPayStatusAPI == api) {
       NSMutableArray *marr = [SAPayStatusModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
       for (SAPayStatusModel *model in marr) {
           if (model.status == 2) {
               [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
               !self.successedBlock ?: self.successedBlock(@"1");
               [self.timer invalidate];
               self.timer = nil;;
               [self.navigationController popViewControllerAnimated:YES];
               return;
           }
       }
   }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.marketingPayStatusAPI == api) {

    }
}

#pragma mark - event
- (void)timerFired {
    self.marketingPayStatusAPI.orderNo = self.orderModel.orderNo;
    [self.marketingPayStatusAPI submitForm:GET];
}

//微信支付订单
-(void)wxPayOrder {
    
    PayReq *rep = [[PayReq alloc] init];
    if ([WXApi isWXAppInstalled]) {
        rep.openID = self.orderModel.appid;
        rep.partnerId = self.orderModel.partnerId;
        rep.prepayId = self.orderModel.prepayId;
        rep.package = self.orderModel.packageValue;
        rep.nonceStr = self.orderModel.noncestr;
        rep.timeStamp = [self.orderModel.timestamp intValue];
        rep.sign = self.orderModel.sign;
        [WXApi sendReq:rep completion:^(BOOL success) {
            [Prompt popPromptViewWithMsg:@"请安装微信客户端" duration:2];
        }];
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [Prompt popPromptViewWithMsg:@"请安装微信客户端" duration:2];
        });
    }
}

-(void)wxCancelPay {
    if (self.timer != nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [self.webView startLoadUrl];
}

-(void)backToLastVC {
    !self.successedBlock ?: self.successedBlock(@"0");
    [self.timer invalidate];
    self.timer = nil;;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - initUI
-(void)initUI {
    
    HDWKWebView *webView = [[HDWKWebView alloc] initWithConfig:@[@"go2Pay",@"goBack"] frame:CGRectMake(0, 44, kScreenWidth, kScreenHeight)];
    self.webView = webView;
    webView.url = self.url;
    webView.isAdaptive = YES;
    webView.openVipDic = self.dataDic;
    [webView startLoadUrl];
    WeakSelf
    webView.jsActionBlock = ^(NSString *name, id body) {
        if ([name isEqualToString:@"go2Pay"]) {
            NSString *str = [NSString stringWithFormat:@"%@",body[@"data"]];
            [weakSelf createOrder:str];
        }
        if ([name isEqualToString:@"goBack"]) {
            [weakSelf backToLastVC];
        }
    };
    [self.view addSubview:webView];
}

//创建订单
-(void)createOrder:(NSString *)serviceId {
    self.growthCreateOrderAPI.marketId = serviceId;
    [self.growthCreateOrderAPI sendRequestToServerWithType:POST];
}

-(SAMarketingAppCreateOrderAPI *)growthCreateOrderAPI {
    if (!_growthCreateOrderAPI) {
        _growthCreateOrderAPI = [SAMarketingAppCreateOrderAPI apiWithDelegate:self];
    }
    return _growthCreateOrderAPI;
}

-(SAMarketingPayStatusAPI *)marketingPayStatusAPI {
    if (!_marketingPayStatusAPI) {
        _marketingPayStatusAPI = [SAMarketingPayStatusAPI apiWithDelegate:self];
    }
    return _marketingPayStatusAPI;
}

-(void)dealloc {
    HDLog(@"%@ 控制器已经被释放",NSStringFromClass([self class]));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

